package org.september.pisces.user.permission.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.september.core.constant.SpecialCharConst;
import org.september.core.exception.BusinessException;
import org.september.pisces.user.permission.entity.RolePermission;
import org.september.pisces.user.permission.vo.PermissionTreeNode;
import org.september.pisces.user.permission.vo.TreeItem;
import org.september.smartdao.CommonDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class PiscesPermissionService {

	private List<String> publicUrls= new ArrayList<>();
	
	private List<String> defaultUrls= new ArrayList<>();
	
	private static Map<String,PermissionTreeNode> permissionDataMap = new HashMap<>();
	
	@Autowired
	private CommonDao dao;
	
	@Autowired
	private SystemUserService systemUserService;
	
	public PiscesPermissionService() {
//		publicUrls.add("/doLogin");
//		publicUrls.add("/doLogout");
//		publicUrls.add("/404");
//		publicUrls.add("/503");
//		publicUrls.add("/frame/index");
	}
	public boolean isPublic(String url) {
		return publicUrls.contains(url);
	}
	
	public boolean isDefault(String url) {
		return defaultUrls.contains(url);
	}
	
	public void addPublicUrl(String url) {
		publicUrls.add(url);	
	}
	
	public void addDefaultUrl(String url) {
		defaultUrls.add(url);	
	}
	
	public void clonePermission(Long srcRoleId,Long newRoleId) {
		RolePermission rp = new RolePermission();
		rp.setRoleId(srcRoleId);
		List<RolePermission> list = dao.listByExample(rp);
		List<RolePermission> newList = new ArrayList<>();
		for(RolePermission perm : list) {
			RolePermission newPerm = new RolePermission();
			newPerm.setRoleId(newRoleId);
			newPerm.setResource(perm.getResource());
			newList.add(newPerm);
		}
		dao.batchInsert(RolePermission.class, newList);
	}
	
	@Transactional
	public void doGrantPermission(Long roleId, String paths){
		// 比较新老权限的差异
        List<RolePermission> persistPerms = systemUserService.getPermissionOfRole(roleId);
        List<RolePermission> removeList = new ArrayList<>();
        List<RolePermission> addList = new ArrayList<>();
        List<String> peristResList = new ArrayList<>();
        List<String> newList = new ArrayList<>();
        for(String path : paths.split(SpecialCharConst.Semicolon)) {
        	newList.addAll(getResourceByPath(path));
        }
        
        for(RolePermission perm : persistPerms) {
        	peristResList.add(perm.getResource());
        }
        for(RolePermission perm : persistPerms) {
        	if(!newList.contains(perm.getResource())) {
        		removeList.add(perm);
        	}
        }
        for(String res : newList) {
        	if(!peristResList.contains(res)) {
        		addList.add(new RolePermission(roleId,res));
        	}
        }
        
        if (addList.isEmpty() && removeList.isEmpty()) {
            throw new BusinessException("没有修改任何权限，无需审核！");
        }
        
        for(RolePermission perm : removeList) {
        	dao.delete(perm);
        }
        for(RolePermission perm : addList) {
        	dao.save(perm);
        }
	}
	
	public Collection<PermissionTreeNode> getAllPermissions() {
		return permissionDataMap.values();
	}
	
	public List<String> getResourceByPath(String path) {
		PermissionTreeNode data = permissionDataMap.get(path);
		if(data!=null) {
			return data.getResource();
		}
		return new ArrayList<>();
	}
	
	public List<TreeItem> toTreeItem(PermissionTreeNode perm){
		String[] arr = perm.getPath().split("-");
		String path = "";
		List<TreeItem> result = new ArrayList<>();
		for(int i=0;i<arr.length;i++) {
			TreeItem ti = new TreeItem();
			if(i==0) {
				ti.setText(arr[i]);
				path = arr[i];
				ti.setPath(path);
				ti.setId(path);
			}else {
				ti.setText(arr[i]);
				ti.setParentId(path);
				path += "-"+arr[i];
				ti.setPath(path);
				ti.setId(path);
			}
			result.add(ti);
		}
		return result;
	}
	
	public void selectTreeItem(List<TreeItem> tiList,long roleId) {
		RolePermission vo = new RolePermission();
		vo.setRoleId(roleId);
		List<RolePermission> list = dao.listByExample(vo);
		
		for(RolePermission rp : list) {
			for(TreeItem ti : tiList) {
				selectTreeItem(ti , rp);
			}
		}
	}
	
	public void selectTreeItem(TreeItem ti,RolePermission perm) {
		List<String> resList = getResourceByPath(ti.getPath());
		if(resList!=null) {
			if(resList.contains(perm.getResource())) {
				ti.setCheckFlag(1);
			}
		}
	}
	
	public static void addPermissionData(String path , String... reses) {
		PermissionTreeNode pd = new PermissionTreeNode();
		pd.setPath(path);
		for(String res : reses) {
			pd.getResource().add(res);
		}
		permissionDataMap.put(path, pd);
	}
	
}

